package cn.edu.seu.herald.informationplatform.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Vote;
import cn.edu.seu.herald.informationplatform.bean.league.VoteItem;
import cn.edu.seu.herald.informationplatform.bean.league.VoteResult;
import cn.edu.seu.herald.informationplatform.dao.cookie.CommonUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteDataAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteItemDataAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteResultDataAccess;

public class VoteServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		int leagueId = Integer.valueOf(request.getParameter("league"));
		try {
			String itemIdParam = request.getParameter("item");
			int itemId = Integer.valueOf(itemIdParam);
			
			CommonUserSessionCookieAccess coSessionCookieAccess =
					new CommonUserSessionCookieAccess(request);
			int userId = coSessionCookieAccess.getUserId();

			VoteDataAccess vdao = VoteDataAccess.getInstance();
			VoteItemDataAccess vidao = VoteItemDataAccess.getInstance();
			VoteResultDataAccess vrdao = VoteResultDataAccess.getInstance();
			
			if (vrdao.contains(userId, itemId)) {
				response.sendRedirect("./polling.jsp?league="+leagueId+"&msg=2");//已投
				return;
			}

			Vote vote = vdao.getVoteByLeagueId(leagueId);
			int voteId = vote.getId();
			VoteItem voteItem = vidao.getVoteItemById(itemId);
			int availableNumber = voteItem.getVote().getAvailableNumber();
			int currentNumber = vrdao.getVoteResultNumber(userId, voteId);
			if (currentNumber < availableNumber) {
				vrdao.createNewVoteResult(userId, itemId);
				response.sendRedirect("./polling.jsp?league="+leagueId+"&msg=1");//成功
				return;
			} else {
				response.sendRedirect("./polling.jsp?league="+leagueId+"&msg=3");//超过选择数
				return;
			}

		} catch (Exception e) {
			response.sendRedirect("./polling.jsp?league="+leagueId+"&msg=0");//身份错误
			return;
		}
	}

}
